package up7.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;

public class UtilsTool {

    /// <summary>
    /// sm4-cbc-pkcs7padding-块对齐大小
    /// </summary>
    public static int sm4AlignBlockSize(int blockSize){
        int len = blockSize % 16;
        len = 16 - len;
        return blockSize + len;
    }

    public static ByteArrayOutputStream unCompress(ByteArrayOutputStream s, String tp)
    {
        if (tp=="zip") return unZip(s);
        return unGzip(s);
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="s"></param>
    /// <param name="type">gzip,zip</param>
    /// <returns></returns>
    public static ByteArrayOutputStream unGzip(ByteArrayOutputStream s) {

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(s.toByteArray());
        try
        {
            GZIPInputStream ungzip = new GZIPInputStream(in);
            byte[] buffer = new byte[1024];
            int n;
            while ((n = ungzip.read(buffer)) >= 0)
            {
                out.write(buffer, 0, n);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return out;
    }

    public static ByteArrayOutputStream unZip(ByteArrayOutputStream s) {
        ByteArrayInputStream bin =new ByteArrayInputStream(s.toByteArray());
        InflaterInputStream iis = new InflaterInputStream(bin);
        ByteArrayOutputStream o = new ByteArrayOutputStream();

        try {

            byte[] buf = new byte[1024];
            int i=0;

            while ((i = iis.read(buf)) > 0) {
                o.write(buf, 0, i);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return o;
    }
}
